/*
 * @author zzr
 * @date: 2025/10/18  17:52
 * @description: 根据后序遍历和中序遍历构建二叉树
 */
public class Demo31 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public int postIndex;

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        postIndex = postorder.length - 1;
        return buildTreeChild(postorder, inorder, 0, postorder.length - 1);
    }

    private TreeNode buildTreeChild(int[] postorder, int[] inorder, int inbegin, int inend) {

        if (inbegin > inend) return null;

        TreeNode root = new TreeNode(postorder[postIndex]);

        int rootIndex = findIndex(inorder, inbegin, inend, postorder[postIndex]);
        if (rootIndex == -1) return null;

        postIndex--;
        // 后序遍历是 左右根
        // 根据后序遍历反推二叉树的时候，是从后面遍历，所以遍历应该是先根再右最后左
        root.right = buildTreeChild(postorder, inorder, rootIndex + 1, inend);
        root.left = buildTreeChild(postorder, inorder, inbegin, rootIndex - 1);
        return null;
    }

    private int findIndex(int[] inorder, int inbegin, int inend, int key) {
        for (int i = inbegin; i <= inend; i++) {
            if (inorder[i] == key) {
                return i;
            }
        }
        return -1;
    }
}
